package com.oolatina.activity;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.mayashree.manager.PageManager;
import com.oolatina.R;
import com.oolatina.SCAudioPlayer;
import com.oolatina.SCButton;
import com.oolatina.SCImage;
import com.oolatina.SCItunesPartner;
import com.oolatina.SCLabel;
import com.oolatina.adapters.KindAdapter;
import com.oolatina.adapters.MusicAdapter;
import com.oolatina.fragments.AgendaFragment;
import com.oolatina.fragments.AudioFragment;
import com.oolatina.fragments.BaseFragment;
import com.oolatina.fragments.LeftMenuFragment;
import com.oolatina.fragments.NewsFragment;
import com.oolatina.fragments.RadioViewFragment;
import com.oolatina.fragments.VideoFragment;
import com.oolatina.modal.Consts;
import com.roomorama.caldroid.CaldroidFragment;
import com.roomorama.caldroid.CaldroidListener;

public class MainActivity extends ActionBarActivity {
	SCImage thumbnailRadio;
	SCLabel labelSong;
	FrameLayout linearLayout;
	SCButton buttonPlay;
	SCAudioPlayer mPlayer;
	SCLabel labelRadio;
	SCItunesPartner itunesPartner;
	public String itunesURL;
	public String coverURL;
	public String songTitle;
	int ScreenWidth;
	int ScreenHeight;
	String radioCurrentPlay;
	boolean radioPlaying;
	int firstLaunch;
	int nWidth;
	private Activity context;
	private View popup_kind_picker;
	private View popup_music_picker;
	private CaldroidFragment dialogCaldroidFragment;
	private ImageButton agendaSearch;
	private LayoutInflater inflater_popup;
	private Object view;
	private DrawerLayout mDrawerLayout;
	private FrameLayout mDrawerFrameLayout;
	private LeftMenuFragment leftMenuFrag;
	private ActionBarDrawerToggle mDrawerToggle;
	private ActionBar actionBar;
	protected PageManager pageManager = new PageManager(this,
			Consts.MAX_PAGE_BUFFER);
	private BaseFragment currentFragment;

	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {

			Consts.dip = (int) TypedValue.applyDimension(
					TypedValue.COMPLEX_UNIT_DIP, (float) 1, getResources()
							.getDisplayMetrics());

		} catch (Exception e) {
			System.out.print(e.getLocalizedMessage());
		}
		
		context = this;
		
		/*
		 * if (savedInstanceState == null) {
		 * getSupportFragmentManager().beginTransaction() .add(R.id.container,
		 * new PlaceholderFragment()) .commit(); }
		 */

		// this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		// Remove notification bar
		// this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
		// WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_main);

		WindowManager wm = (WindowManager) this
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();
		ScreenWidth = display.getWidth();
		ScreenHeight = display.getHeight();

		linearLayout = (FrameLayout) findViewById(R.id.fragment_content);

		// Customize the ActionBar
		actionBar = getSupportActionBar();
		// enable ActionBar app icon to behave as action to toggle nav drawer
		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setHomeButtonEnabled(true);
		actionBar.setTitle("");
		actionBar.setIcon(R.drawable.transparentbg);

		// Set the custom Title Center Logo layout
		ActionBar.LayoutParams lp = new ActionBar.LayoutParams(
				ActionBar.LayoutParams.WRAP_CONTENT,
				ActionBar.LayoutParams.WRAP_CONTENT, Gravity.CENTER);

		View customNav = LayoutInflater.from(this).inflate(
				R.layout.layout_acbcustomview, null); // layout which contains
														// your button.
		actionBar.setCustomView(customNav, lp);
		actionBar.setDisplayShowCustomEnabled(true);

		inflater_popup = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		/*** THis will be used to creatre a custom action bar click listener **/
		View v = actionBar.getCustomView();
		agendaSearch = (ImageButton) v.findViewById(R.id.search);
		agendaSearch.setVisibility(View.INVISIBLE);
		/*** sample click is a id of the view i have used in action bar view ***/
		v.findViewById(R.id.search).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						final View popup_search_agenda = inflater_popup
								.inflate(R.layout.popup_search_agenda, null,
										false);

						final PopupWindow pw = new PopupWindow(popup_search_agenda,
								ScreenWidth - 50, ScreenHeight - 150, true);
						pw.setBackgroundDrawable(new BitmapDrawable());
						pw.setOutsideTouchable(true);
						pw.setFocusable(true);

						// The code below assumes that the root container has an
						// id called 'main'
						pw.showAtLocation(findViewById(R.id.fragment_content), Gravity.CENTER,
								0, 65);
						
						createPopupKindSelector(popup_search_agenda);
						createPopupMusicSelector(popup_search_agenda);
						createPopupDateSelector(popup_search_agenda, savedInstanceState);
						
						Button btnSearch = (Button) popup_search_agenda
								.findViewById(R.id.btnSearch);
						btnSearch
								.setOnClickListener(new View.OnClickListener() {

									@Override
									public void onClick(View v) {
										EditText txtCity = (EditText) popup_search_agenda
												.findViewById(R.id.txtCity);
										EditText txtCalendar = (EditText) popup_search_agenda
												.findViewById(R.id.txtCalendar);
										EditText txtRecherche = (EditText) popup_search_agenda
												.findViewById(R.id.txtRecherche);
										EditText txtMusic = (EditText) popup_search_agenda
												.findViewById(R.id.txtMusic);
										EditText txtKind = (EditText) popup_search_agenda
												.findViewById(R.id.txtKind);

										// if (txtCity.getText().toString()) {
										//
										// }
										((AgendaFragment) currentFragment)
												.checkWebServices(txtKind
														.getText().toString(),
														txtMusic.getText()
																.toString(),
														txtRecherche.getText()
																.toString(),
														txtCalendar.getText()
																.toString(),
														txtCity.getText()
																.toString());
										pw.dismiss();

									}
								});
					}
				});

		
		mDrawerLayout = (DrawerLayout) findViewById(R.id.menu_layout);
		mDrawerFrameLayout = (FrameLayout) findViewById(R.id.left_drawer);

		// set a custom shadow that overlays the main content when the drawer
		// opens
		mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
				GravityCompat.START);
		// set up the drawer's list view with items and click listener
		// Setup the drawer with the LeftMenu Fragment
		leftMenuFrag = new LeftMenuFragment();

		FragmentManager fragmentManager = getSupportFragmentManager();
		fragmentManager.beginTransaction()
				.replace(R.id.left_drawer, leftMenuFrag).commit();

		// ActionBarDrawerToggle ties together the the proper interactions
		// between the sliding drawer and the action bar app icon
		mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
		mDrawerLayout, /* DrawerLayout object */
		R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
		R.string.drawer_open, /* "open drawer" description for accessibility */
		R.string.drawer_close /* "close drawer" description for accessibility */
		) {
			public void onDrawerClosed(View view) {
				// actionBar.setTitle(mTitle);
				// invalidateOptionsMenu(); // creates call to
				// onPrepareOptionsMenu()
			}

			public void onDrawerOpened(View drawerView) {
				// actionBar.setTitle(mDrawerTitle);
				// invalidateOptionsMenu(); // creates call to
				// onPrepareOptionsMenu()
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		currentFragment = new RadioViewFragment();
		showAsRootScreen(currentFragment);

	}

	private void createPopupDateSelector(final View popup_search_agenda, Bundle savedInstanceState) {

		EditText txtCalendar = (EditText)popup_search_agenda.findViewById(R.id.txtCalendar);
		txtCalendar.setFocusable(false);
		txtCalendar.setKeyListener(null);
		final Bundle state = savedInstanceState;
		txtCalendar.setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// Setup caldroid to use as dialog
						dialogCaldroidFragment = new CaldroidFragment();
						dialogCaldroidFragment.setCaldroidListener(new CaldroidListener() {
							
							@Override
							public void onSelectDate(Date date, View view) {
								
								// for your date format use
								SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
								// set a string to format your current date
								String dateStr = sdf.format(date);
								
								EditText txtCalendar = (EditText) popup_search_agenda
										.findViewById(R.id.txtCalendar);
								txtCalendar.setText(dateStr);
								dialogCaldroidFragment.dismiss();
							}
						});

						// If activity is recovered from rotation
						final String dialogTag = "CALDROID_DIALOG_FRAGMENT";
						if (state != null) {
							dialogCaldroidFragment.restoreDialogStatesFromKey(
									getSupportFragmentManager(), state,
									"DIALOG_CALDROID_SAVED_STATE", dialogTag);
							Bundle args = dialogCaldroidFragment.getArguments();
							if (args == null) {
								args = new Bundle();
								dialogCaldroidFragment.setArguments(args);
							}
							args.putString(CaldroidFragment.DIALOG_TITLE,
									"Select a date");
						} else {
							// Setup arguments
							Bundle bundle = new Bundle();
							// Setup dialogTitle
							bundle.putString(CaldroidFragment.DIALOG_TITLE,
									"Select a date");
							dialogCaldroidFragment.setArguments(bundle);
						}

						dialogCaldroidFragment.show(getSupportFragmentManager(),
								dialogTag);


					}
				});

	}
	
	private void createPopupMusicSelector(final View popup_search_agenda) {
		EditText txtRecherche = (EditText)popup_search_agenda.findViewById(R.id.txtRecherche);
//		txtRecherche.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//			
//			@Override
//			public void onFocusChange(View v, boolean hasFocus) {
//				// TODO Auto-generated method stub
//				
//			}
//		});
		EditText txtMusic = (EditText)popup_search_agenda.findViewById(R.id.txtMusic);
		txtMusic.setFocusable(false);
		txtMusic.setKeyListener(null);
		txtMusic.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				popup_kind_picker = inflater_popup.inflate(
						R.layout.popup_music_picker, null, false);
				final PopupWindow pwMusicPicker = new PopupWindow(
						popup_kind_picker, ScreenWidth - 40,
						ScreenHeight - 220, true);
				pwMusicPicker.setBackgroundDrawable(new BitmapDrawable());
				pwMusicPicker.setOutsideTouchable(true);
				pwMusicPicker.setFocusable(true);

				ListView musicListView = (ListView) popup_kind_picker
						.findViewById(R.id.musicList);
				final MusicAdapter musicAdapter = new MusicAdapter(
						context, context);
				musicListView.setAdapter(musicAdapter);
				musicListView.setOnItemClickListener(musicAdapter);

				Button doneButton = (Button) popup_kind_picker
						.findViewById(R.id.btnMusicDone);
				doneButton
						.setOnClickListener(new View.OnClickListener() {

							@Override
							public void onClick(View v) {

								EditText txtMusic = (EditText) popup_search_agenda
										.findViewById(R.id.txtMusic);
								String value = musicAdapter
										.getChosenStrings().toString();
								txtMusic.setText(value.substring(1,
										value.length() - 1));
								pwMusicPicker.dismiss();
							}
						});

				// The code below assumes that the root container has an
				// id called 'main'
				pwMusicPicker.showAtLocation(
						findViewById(R.id.fragment_content),
						Gravity.CENTER, 0, 80);
				// dialogFrag.show();
			}
		});
		
	}

	private void createPopupKindSelector(final View popup_search_agenda) {

		EditText txtKind = (EditText)popup_search_agenda.findViewById(R.id.txtKind);
		txtKind.setFocusable(false);
		txtKind.setKeyListener(null);
		txtKind.setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						if (popup_kind_picker == null) {
//							return false;
						}
						popup_kind_picker = inflater_popup.inflate(
								R.layout.popup_kind_picker, null, false);
						final PopupWindow pwKindPicker = new PopupWindow(
								popup_kind_picker, ScreenWidth - 40,
								ScreenHeight - 250, true);
						pwKindPicker.setBackgroundDrawable(new BitmapDrawable());
						pwKindPicker.setOutsideTouchable(true);
						pwKindPicker.setFocusable(true);

						ListView kindListView = (ListView) popup_kind_picker
								.findViewById(R.id.kindList);
						final KindAdapter kindAdapter = new KindAdapter(
								context, context);
						kindListView.setAdapter(kindAdapter);
						kindListView.setOnItemClickListener(kindAdapter);

						Button doneButton = (Button) popup_kind_picker
								.findViewById(R.id.btnKindDone);
						doneButton
								.setOnClickListener(new View.OnClickListener() {

									@Override
									public void onClick(View v) {

										EditText txtKind = (EditText) popup_search_agenda
												.findViewById(R.id.txtKind);
										String value = kindAdapter
												.getChosenStrings().toString();
										txtKind.setText(value.substring(1,
												value.length() - 1));
										pwKindPicker.dismiss();
									}
								});

						// The code below assumes that the root container has an
						// id called 'main'
						pwKindPicker.showAtLocation(
								findViewById(R.id.fragment_content),
								Gravity.CENTER, 0, 80);
						// dialogFrag.show();
					}
				});

	}

	
	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {
		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main, container,
					false);
			return rootView;
		}
	}

	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:

			if (!mDrawerLayout.isDrawerOpen(Gravity.LEFT))
				mDrawerLayout.openDrawer(Gravity.LEFT);
			else
				mDrawerLayout.closeDrawer(Gravity.LEFT);

			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public void onLeftMenuClicked(int position) {
		mDrawerLayout.closeDrawer(Gravity.LEFT);
		agendaSearch.setVisibility(View.INVISIBLE);
		BaseFragment frag = null;
		switch (position) {
		case 0:
			// NEWS
			if (!currentFragment.getClass().equals(NewsFragment.class)) {
				frag = new NewsFragment();
			}
			break;
		case 1:
			// Agenda
			agendaSearch.setVisibility(View.VISIBLE);
			if (!currentFragment.getClass().equals(AgendaFragment.class)) {
				frag = new AgendaFragment();
				
			}
			break;
		case 2:
			// Audio
			if (!currentFragment.getClass().equals(AudioFragment.class)) {
				frag = new AudioFragment();
			}
			break;
		case 3:
			// Video
			if (!currentFragment.getClass().equals(VideoFragment.class)) {
				frag = new VideoFragment();
			}
			break;
		case 4:
			// Radio
			if (!currentFragment.getClass().equals(RadioViewFragment.class)) {
				frag = new RadioViewFragment();
			}

			break;

		default:
			break;
		}

		if (frag != null) {
			showAsRootScreen(frag);
			currentFragment = frag;
		}

	}

	/*
	 * Method called to save a tag Object to the previous Fragment in the stack.
	 * This is used to communicate to the previous stack
	 * 
	 * @param tag An Object saved to the previous fragment in the stack
	 */
	public void setTagToPreviousState(Object tag) {
		pageManager.setTagToPreviousState(tag);
	}

	/**
	 * This method is called when the fragment that we want to add as the next
	 * in the stack
	 * 
	 * @param fragment
	 */
	public void showNextScreen(BaseFragment fragment) {
		currentFragment = fragment;
		pageManager.pushScreen(fragment);

	}

	/*
	 * This method is called when the fragment that we want to add has to be
	 * added as the root fragment, thus clearing the stack
	 * 
	 * @param fragment
	 */
	public void showAsRootScreen(BaseFragment fragment) {
		currentFragment = fragment;
		pageManager.pushAsRootScreen(fragment);
	}
	
	@Override
	public void onBackPressed() {
		if (!pageManager.onBackPressed()) {
			super.onBackPressed();
		}
	}

	/**
	 * @return of type
	 * @since Dec 6, 2013
	 * @author Hari K J
	 */
	public Object getTagFromPreviousState() {
		return pageManager.getTagFromPreviousState();
	}

	public void callNewsDetail(String newsTitle, String detail, String url) {

		Intent in = new Intent(MainActivity.this, NewsDetail.class);

		in.putExtra("title", newsTitle);
		in.putExtra("detail", detail);
		in.putExtra("url", url);
		startActivity(in);

	}

}
